package leetcode.D100.T25;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: 18362
 * @Create: 2022-03-10 20:27:02 星期四
 */

class Solution {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode tail = head;
        int length = 1;
        while (tail != null && length < k) {
            length++;
            tail = tail.next;
        }
        if (tail == null) {
            return head;
        } else {
            ListNode thead = reverseKGroup(tail.next, k);
            tail.next = thead;
            return reverseK(head, k);
        }
    }

    private ListNode reverseK(ListNode head, int k) {
        if (k <= 1 || head == null || head.next == null)
            return head;
        ListNode tHead = reverseK(head.next, k - 1);
        ListNode tail = head.next, successor = tail.next;
        tail.next = head;
        head.next = successor;
        return tHead;
    }
}